package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        setmealMapper.add(setmeal);

        setSetmealAssociationGroup(setmeal.getId(), checkgroupIds);

        if (setmeal.getImg() != null) {
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        List<Setmeal> setmealList = setmealMapper.findPageByCondition(queryString);
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmealList = setmealMapper.findAll();
        return setmealList;
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealMapper.findById(id);
    }

    @Override
    public Map getSetmealReport() {
        List<Map> list = setmealMapper.getSetmealReport();

        List<String> names = new ArrayList<>();
        for (Map map : list) {
            String name = (String) map.get("name");
            names.add(name);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("setmealNames", names);
        map.put("setmealCounts", list);

        return map;
    }

    private void setSetmealAssociationGroup(Integer id, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setmealMapper.setSetmealAssociationGroup(id, checkgroupIds);
        }
    }
}
